package etnorservice.etnor_service.utils;



import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;

@Slf4j
public class ShellUtils {

    public static CompletableFuture<Integer> executeAsync(String command, String workDir, Consumer<String> outputHandler) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                ProcessBuilder processBuilder = new ProcessBuilder();
                if (System.getProperty("os.name").toLowerCase().contains("windows")) {
                    processBuilder.command("cmd.exe", "/c", command);
                } else {
                    processBuilder.command("bash", "-c", command);
                }

                if (workDir != null) {
                    processBuilder.directory(new File(workDir));
                }

                Process process = processBuilder.start();

                // 异步读取输出
                new BufferedReader(new InputStreamReader(process.getInputStream())).lines()
                        .forEach(line -> {
                            log.debug(line);
                            if (outputHandler != null) {
                                outputHandler.accept(line);
                            }
                        });

                // 异步读取错误
                new BufferedReader(new InputStreamReader(process.getErrorStream())).lines()
                        .forEach(line -> {
                            log.error(line);
                            if (outputHandler != null) {
                                outputHandler.accept("ERROR: " + line);
                            }
                        });

                return process.waitFor();
            } catch (Exception e) {
                log.error("执行命令失败: {}", command, e);
                throw new RuntimeException("执行命令失败: " + e.getMessage());
            }
        });
    }
}